<?php

namespace falcon5\inc\Helpers;

use falcon5\inc\Base\Common;
use falcon5\inc\Base\WPOption;
use falcon5\inc\Base\WPUrlMode;
use hollisho\helpers\ArrayHelper;
use lucatume\DI52\ContainerException;

/**
 * eg：
 * $path = UrlHelper::getPath();  // return: /example/path
 * $fullPath = UrlHelper::getPath(true);  // return: /example/path?param=value
 * $query = UrlHelper::getQuery();  // return: param=value
 * $queryWithMark = UrlHelper::getQuery(true);  // return: ?param=value
 *
 * Class UrlHelper
 * @package falcon5\inc\Helpers
 * @desc
 */
class UrlHelper
{

    /**
     * 检查URL模式（子域名或子目录）
     * @param string $host 主机名
     * @param string $path URL路径
     * @return array|null 返回模式信息数组或null
     */
    public static function checkUrlMode(string $host, string $path)
    {
        // 检查是否是子域名模式
        if (preg_match('/^(' . Common::LANG_PATTERN . ')\./i', $host, $matches)) {
            return [
                'lang' => $matches[1],
                'path' => rawurldecode($path),
                'type' => 'subdomain',
                'mainHost' => preg_replace('/^' . $matches[1] . '\./i', '', $host)
            ];
        }
        
        // 检查是否是子目录模式
        if (preg_match('/^\/(' . Common::LANG_PATTERN . ')\/(.*)/i', $path, $matches)) {
            return [
                'lang' => $matches[1],
                'path' => '/' . rawurldecode($matches[2]),
                'type' => 'subfolder',
                'mainHost' => $host
            ];
        }
        
        return null;
    }

    /**
     * 获取当前URL中的语言代码（支持子域名和子目录两种模式）
     * @return array|null 返回包含语言代码和路径的数组，如果没有匹配则返回null
     */
    public static function getUrlInfo()
    {
        // 获取当前主机名和请求URI
        $host = $_SERVER['HTTP_HOST'];
        $request_uri = $_SERVER['REQUEST_URI'];
        $url_params = explode('?', $request_uri);
        $path = $url_params[0];

        return self::checkUrlMode($host, $path);
    }
    public static function getUrlPathInfo($host=null)
    {
        // 获取当前主机名和请求URI
        $host = $host??$_SERVER['HTTP_HOST'];
        $request_uri = $_SERVER['REQUEST_URI'];
        $url_params = explode('?', $request_uri);
        $path = $url_params[0];

        return $path;
    }
    /**
     * @return mixed
     * @throws \hollisho\helpers\InvalidArgumentException
     */
    public static function getCurrentLang()
    {
        return ArrayHelper::getValue(self::getUrlInfo(), 'lang');
    }


    /**
     * 获取当前请求的路径部分
     * @param bool $withQueryString 是否包含查询字符串
     * @return string
     */
    public static function getPath(bool $withQueryString = false): string
    {
        $request_uri = $_SERVER['REQUEST_URI'];
        if (!$withQueryString) {
            $url_params = explode('?', $request_uri);
            return $url_params[0];
        }
        return $request_uri;
    }

    /**
     * 获取当前请求的查询字符串
     * @param bool $withQuestionMark 是否在返回的查询字符串前添加问号
     * @return string
     */
    public static function getQuery(bool $withQuestionMark = false): string
    {
        $request_uri = $_SERVER['REQUEST_URI'];
        $url_params = explode('?', $request_uri);
        
        if (isset($url_params[1])) {
            return $withQuestionMark ? '?' . $url_params[1] : $url_params[1];
        }
        
        return '';
    }

    public static function getProtocol(): string
    {
        return ((isset($_SERVER['HTTPS']) and ($_SERVER['HTTPS'] == 'on' or $_SERVER['HTTPS'] == 1)) or (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) and  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';
    }

    public static function getHost(): string
    {
        $host = falcon5_env('FC5_TARGET_HOST');
        if ($host) {
            return $host;
        }

        if ( ! empty( $_SERVER['HTTP_HOST'] ) ) {
            $host = function_exists( 'mb_strtolower' ) ? mb_strtolower( $_SERVER['HTTP_HOST'] ) : strtolower( $_SERVER['HTTP_HOST'] );
            // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
            $host = htmlentities( $host, ENT_COMPAT );
        } elseif ( PHP_SAPI === 'cli' && function_exists( 'get_option' ) ) {
            $host = (string) parse_url( get_option( 'home' ), PHP_URL_HOST );
        } else {
            $host = '';
        }

        return $host;
    }


    /**
     * url redirect
     * @param string $url
     * @param int $responseCode
     */
    public static function redirect(string $url, int $responseCode = 302)
    {
        header('Location: ' . $url, true, $responseCode);
        exit;
    }

    /**
     * 获取浏览器语言列表
     * @return array
     */
    public static function getBrowserLanguages(): array
    {
        $languages = [];
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            // 解析 HTTP_ACCEPT_LANGUAGE
            $acceptLanguages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            foreach ($acceptLanguages as $language) {
                $lang = explode(';', $language)[0];
                $lang = strtolower(trim($lang));
                $languages[] = $lang;
            }
        }
        return array_unique($languages);
    }

    /**
     * 查找最佳匹配语言
     * @param array $browserLanguages
     * @param array $allowedLanguages
     * @return string|null
     */
    public static function findBestLanguage(array $browserLanguages, array $allowedLanguages)
    {
        foreach ($browserLanguages as $browserLang) {
            foreach ($allowedLanguages as $allowedLang) {
                if (strpos($browserLang, strtolower($allowedLang)) === 0) {
                    return $allowedLang;
                }
            }
        }
        return null;
    }

    /**
     * 生成重定向URL
     * @param string $lang
     * @param string $path
     * @param string $query
     * @return string
     * @throws ContainerException
     */
    public static function generateRedirectUrl(string $lang, string $path, string $query): string
    {
        /** @var WPOption $falcon5Option */
        $falcon5Option = falcon5_app(WPOption::class);
        $urlMode = $falcon5Option->getUrlMode(); // 假设有这个方法获取URL模式配置

        $protocol = self::getProtocol();
        $host = self::getHost();

        if ($urlMode === WPUrlMode::URL_MODE_SUBDOMAIN) {
            // 子域名模式
            $host = preg_replace('/^www\./', '', $host);
            return sprintf('%s://%s.%s%s%s', 
                $protocol,
                $lang,
                $host,
                $path,
                $query
            );
        } else {
            // 子目录模式
            return sprintf('%s://%s/%s%s%s',
                $protocol,
                $host,
                $lang,
                $path,
                $query
            );
        }
    }
}